package auto.feature;


import auto.device.Phione;
import io.appium.java_client.AppiumBy;
import io.appium.java_client.AppiumDriver;


import org.openqa.selenium.Dimension;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.PointerInput;
import org.openqa.selenium.interactions.Sequence;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;



public class ChatListFeature {
//feature1：此方法用于聊天列表上下滑动屏幕
    public String slideScreen() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;
        //点击进入聊天列表
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]"))).click();

        Map<String, Object> argsUp = new HashMap<>();
        argsUp.put("direction", "up");
        driver.executeScript("mobile: swipe", argsUp);

        // 短暂等待
        Thread.sleep(1000);

        // 向下滑动
        Map<String, Object> argsDown = new HashMap<>();
        argsDown.put("direction", "down");
        driver.executeScript("mobile: swipe", argsDown);

        return "滑动屏幕功能正常";
    }

//feature2：全部已读
    public String allRead(){
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        //点击编辑
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"编辑\"`]"))).click();

        //尝试点击全部已读按钮
        try{
            WebElement allReadButton=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("全部标为已读")));

            if(allReadButton.getAttribute("enabled").equals("true") ){
                allReadButton.click();
                if(chatList.getAttribute("value").equals("1")){
                    return "已全部标记已读";
                }
                else{
                    return "\"全部标为已读\"功能失效";
                }
            }
            else{
                //点击取消
                wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"取消\"`]"))).click();
                return "当前没有未读消息";
            }
        }catch (TimeoutException e){
            System.out.println("全部已读文本按钮消失");
            return "全部已读文本按钮消失";
        }

    }

//feture3：选择消息标记已读
    public String selectRead() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        if(chatList.getAttribute("value").equals("1")){
            System.out.println("当前不存在未读消息");
            return "当前不存在未读信息";
        }

        //点击编辑
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"编辑\"`]"))).click();
        Thread.sleep(1500);

        List<WebElement> messages=driver.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name = '1' OR name = '2' OR name = '3' OR name = '4' OR name = '5' OR name = '6' OR name = '7' OR " +
                "name = '8' OR name = '9'`]"));
        //定位未读的消息,并点击
        messages.get(0).click();

        //点击已读
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("已读"))).click();
        Thread.sleep(2000);

        //判断是不是标记已读成功
        if(messages.size()<=(driver.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name = '1' OR name = '2' OR name = '3' OR name = '4' OR name = '5' OR name = '6' OR name = '7' OR " +
                "name = '8' OR name = '9'`]")).size())){
            System.out.println("未读消息数量未减少");
            return "未读消息数量未减少";
        }

        System.out.println("选择标记已读成功");
        driver.quit();
        return "选择标记已读功能正常";
    }

//feature4：选择消息删除
    public String selectDeleteRead() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        //点击编辑
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"编辑\"`]"))).click();
        Thread.sleep(1500);

        //默认选中第一条
        WebElement firstMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeWindow/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther[1]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]")));

        List<WebElement> staticTexts = firstMessage.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText"));
        String mark1=staticTexts.get(staticTexts.size()-1).getAttribute("value");

        firstMessage.click();
        //点击删除
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("删除"))).click();

        //点击提示框中的删除
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"删除\"`]"))).click();
        Thread.sleep(3000);

        if(driver.findElements(AppiumBy.accessibilityId("没有聊天记录")).size()>0){
            System.out.println("删除消息成功");
            return "删除消息成功";
        }

        //默认选中第一条
        WebElement newFirstMessage=driver.findElement(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]"));

        List<WebElement> newStaticTexts = newFirstMessage.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText"));
        String mark2=newStaticTexts.get(newStaticTexts.size()-1).getAttribute("value");

        if(mark2.equals(mark1)){
            System.out.println("选择删除消息失败");
            return "选择删除消息失败";
        }

        System.out.println("成功选择消息删除");
        driver.quit();
        return "成功选择消息删除";
    }

//feature5:消息右滑置顶+消息左滑删除
    public String pinnedAndSlideDelete() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        //默认指定第二条信息
        WebElement secondMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]" +
                "/XCUIElementTypeOther/XCUIElementTypeOther" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[2]")));


        //获取未置顶前的昵称
        String nickNameOld=secondMessage.findElements(AppiumBy.xpath("//XCUIElementTypeStaticText")).get(0).getAttribute("value");
        System.out.println(nickNameOld);

        //将这条信息短暂的向右滑动
        Map<String, Object> swipeArgs = new HashMap<>();
        swipeArgs.put("direction", "right");
        swipeArgs.put("element", secondMessage); // 指定滑动的元素
        swipeArgs.put("duration", 600); // 滑动持续时间500毫秒
        // 执行滑动操作
        driver.executeScript("mobile: swipe", swipeArgs);
        Thread.sleep(1500);

        try{
            //点击置顶按钮
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("置顶"))).click();
        }catch(TimeoutException e){
            return "置顶按钮消失";
        }
        Thread.sleep(1000);
        //查看第一个元素，看看是不是刚才指定的那个元素
        WebElement firstMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]")));

        //获取未置顶前的昵称
        String nickNameNew=firstMessage.findElements(AppiumBy.xpath("//XCUIElementTypeStaticText")).get(0).getAttribute("value");
        System.out.println(nickNameNew);

        if(nickNameNew.equals(nickNameOld)){
            System.out.println("置顶成功");
        }
        else{
            driver.quit();
            System.out.println("置顶失败");
            return "置顶失败";
        }

        System.out.println("开始左滑删除此消息");
        Map<String, Object> swipeArgs1 = new HashMap<>();
        swipeArgs1.put("direction", "left");
        swipeArgs1.put("element", firstMessage); // 指定滑动的元素
        swipeArgs1.put("duration", 700);
        // 执行滑动操作
        driver.executeScript("mobile: swipe", swipeArgs1);

        try{
            //点击左滑删除按钮
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("删除"))).click();

            //点击弹出的提示框
            wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name == \"同时为对方删除\"`]"))).click();

            //重新定位第一条元素，判断第一条元素有没有被删除
            WebElement newFirstMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                    ("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                            "/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther" +
                            "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]")));

            //获取未置顶前的昵称
            String nickNameNew1=newFirstMessage.findElements(AppiumBy.xpath("//XCUIElementTypeStaticText")).get(0).getAttribute("value");

            if(nickNameNew.equals(nickNameNew1)){
                System.out.println("左滑删除失败");
                driver.quit();
                return "左滑删除失败";
            }
            else{
                System.out.println("左滑删除成功");
            }
        }
        catch(TimeoutException e){
            return "删除按钮丢失，左滑删除失败";
        }

        driver.quit();
        System.out.println("右滑置顶+左滑删除消息功能正常");
        return "右滑置顶+左滑删除消息功能正常";
    }


//feature6：左滑消息，将消息标记为已读
    public String slideMarkRead() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        if(chatList.getAttribute("value").equals("1")){
            System.out.println("当前不存在未读消息");
            driver.quit();
            return "当前不存在未读信息";
        }

        //定位所有的未读消息，数字是未读消息的数量
        List<WebElement> messages=driver.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name = '1' OR name = '2' OR name = '3' OR name = '4' OR name = '5' OR name = '6' OR name = '7' OR " +
                "name = '8' OR name = '9'`]"));
        WebElement firstMessage=messages.get(0);

        // 获取屏幕尺寸,因为不同屏幕滑动的距离不同，所以都让下面向做滑动屏幕一半的距离
        Dimension screenSize = driver.manage().window().getSize();
        int screenWidth = screenSize.getWidth();

        // 获取元素的起始坐标
        int startX = firstMessage.getLocation().getX();
        int startY = firstMessage.getLocation().getY();

        // 设置滑动的终点坐标（滑动屏幕宽度的一半）
        int endX = startX - (screenWidth / 2);
        int endY = startY;

        // 使用 W3C Actions API 执行点击并滑动操作
        PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");
        Sequence swipe = new Sequence(finger, 1);

        // 点击元素开始
        swipe.addAction(finger.createPointerMove(Duration.ZERO, PointerInput.Origin.viewport(), startX, startY));
        swipe.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));

        // 滑动到终点
        swipe.addAction(finger.createPointerMove(Duration.ofMillis(500), PointerInput.Origin.viewport(), endX, endY));
        swipe.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));

        // 执行操作
        driver.perform(Arrays.asList(swipe));

        //点击出现的标记已读
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("已读"))).click();

        //判断是不是标记已读成功了
        List<WebElement> newMessages=driver.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeStaticText[`name = '1' OR name = '2' OR name = '3' OR name = '4' OR name = '5' OR name = '6' OR name = '7' OR " +
                "name = '8' OR name = '9'`]"));
        if(newMessages.size()==messages.size()){
            System.out.println("滑动标记已读失败");
            return "滑动标记已读失败";
        }
        else{
            System.out.println("左滑标记已读成功");
        }

        driver.quit();
        return "标记 已读/未读 成功";
    }

//feature7:左滑消息标记为未读
    public String slideMarkUnRead() throws IOException, InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;

        //首先点击联系人，进入联系人列表
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeButton[`name == \"联系人\"`]"))).click();

        //点击列表中的第一个用户
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeWindow[1]" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                "/XCUIElementTypeOther[2]/XCUIElementTypeOther" +
                "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[5]"))).click();

        //定位文本框元素
        WebElement textBox=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("输入消息")));
        textBox.click();
        textBox.sendKeys("随便输入点东西");

        //点击发送
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("MessagingApp.ConversationInputToolbar._sendButton"))).click();

        //发送完之后返回到主页面
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("icon back blue"))).click();

        //进入到联系人页面，刚才的那条信息是在最上面的
        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        //这就是刚才发送的第一条信息
        WebElement firstMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]")));


        System.out.println("开始左滑标记未读此消息");
        Map<String, Object> swipeArgs1 = new HashMap<>();
        swipeArgs1.put("direction", "left");
        swipeArgs1.put("element", firstMessage); // 指定滑动的元素
        swipeArgs1.put("duration", 700);
        // 执行滑动操作
        driver.executeScript("mobile: swipe", swipeArgs1);
        Thread.sleep(1000);

        //点击出现的标记未读
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("标为未读"))).click();

        System.out.println("请在5秒钟内观察标记未读的红点是否出现");
        Thread.sleep(5000);

        //把这个红点取消掉，方便后续的测试
        //点击编辑
        wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"编辑\"`]"))).click();
        try{
            WebElement allReadButton=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.accessibilityId("全部标为已读")));

            if(allReadButton.getAttribute("enabled").equals("true") ){
                allReadButton.click();
                if(chatList.getAttribute("value").equals("1")){
                    return "已全部标记已读";
                }
                else{
                    return "\"全部标为已读\"功能失效";
                }
            }
            else{
                //点击取消
                wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"取消\"`]"))).click();
                return "当前没有未读消息";
            }
        }catch (TimeoutException e){
            System.out.println("全部已读文本按钮消失");
        }

        driver.quit();
        System.out.println("已成功标记未读");
        return "已经标记为未读";
    }

//feature8:长按预览消息
    public String messagePpreview() throws InterruptedException {
        Phione phione = new Phione();
        AppiumDriver driver = phione.driver;
        WebDriverWait wait = phione.wait;
        //点击进入聊天列表
        WebElement chatList=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain("**/XCUIElementTypeButton[`name == \"聊天\"`]")));
        chatList.click();

        //定位第一条消息并且长按
        WebElement firstMessage=wait.until(ExpectedConditions.visibilityOfElementLocated(AppiumBy.iOSClassChain
                ("**/XCUIElementTypeWindow[1]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther[2]/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther" +
                        "/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeOther/XCUIElementTypeTable/XCUIElementTypeCell[1]")));

        // 获取元素的位置和大小，方便取消预览后再取消
        Rectangle rect = firstMessage.getRect();

        //对这个元素进行长按
        Actions actions = new Actions(driver);

        // 执行长按操作
        actions.clickAndHold(firstMessage)
                .pause(Duration.ofSeconds(2))
                .release()
                .build()
                .perform();

        //判断元素是否出现
        Thread.sleep(2000);

        if(driver.findElements(AppiumBy.iOSClassChain("**/XCUIElementTypeOther[`name == \"预览\"`]/XCUIElementTypeOther[1]")).size()>0){

            // 计算元素中心点的坐标
            int centerX = rect.x + (rect.width / 2);
            int centerY = rect.y + (rect.height / 2);

            // 使用 executeScript 来执行点击操作
            Map<String, Object> params = new HashMap<>();
            params.put("x", centerX);
            params.put("y", centerY);
            driver.executeScript("mobile: tap", params);

            driver.quit();
            System.out.println("长按消息预览成功");
            return "长按消息预览成功";
        }
        else{
            driver.quit();
            System.out.println("长按消息预览失败");
            return "长按消息预览失败";
        }


    }






    //用于图片转码
    public  String encodeImageToBase64(String imagePath) {
        try {
            byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
            String base64Image = Base64.getEncoder().encodeToString(imageBytes);
            return base64Image;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
